package com.warom.sdg.ui;

import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.util.Util;
import com.warom.sdg.R;

/**
 * 视频播放器Activity
 * 用于播放设备直播流
 */
public class VideoPlayerActivity extends AppCompatActivity {
    private static final String TAG = "VideoPlayerActivity";

    private PlayerView playerView;
    private SimpleExoPlayer player;
    private ProgressBar progressBar;
    private TextView titleTextView;
    private ImageButton backButton;
    private ImageButton fullscreenButton;
    
    private String streamUrl;
    private String title;
    private boolean playWhenReady = true;
    private int currentWindow = 0;
    private long playbackPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_player);
        
        // 获取传入的参数
        streamUrl = getIntent().getStringExtra("STREAM_URL");
        title = getIntent().getStringExtra("TITLE");
        
        if (streamUrl == null || streamUrl.isEmpty()) {
            Toast.makeText(this, "未提供视频流URL", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        // 初始化视图
        playerView = findViewById(R.id.player_view);
        progressBar = findViewById(R.id.progress_bar);
        titleTextView = findViewById(R.id.video_title);
        backButton = findViewById(R.id.back_button);
        fullscreenButton = findViewById(R.id.fullscreen_button);
        
        // 设置标题
        if (title != null && !title.isEmpty()) {
            titleTextView.setText(title);
        } else {
            titleTextView.setText("视频播放");
        }
        
        // 设置返回按钮点击事件
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        
        // 设置全屏按钮点击事件
        fullscreenButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleFullscreen();
            }
        });
        
        Log.d(TAG, "准备播放视频流: " + streamUrl);
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        if (Util.SDK_INT >= 24) {
            initializePlayer();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Util.SDK_INT < 24 || player == null) {
            initializePlayer();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (Util.SDK_INT < 24) {
            releasePlayer();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (Util.SDK_INT >= 24) {
            releasePlayer();
        }
    }
    
    /**
     * 初始化ExoPlayer播放器
     */
    private void initializePlayer() {
        if (player == null) {
            // 创建播放器实例
            player = new SimpleExoPlayer.Builder(this).build();
            playerView.setPlayer(player);
            
            // 设置播放器监听器
            player.addListener(new Player.EventListener() {
                @Override
                public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
                    if (playbackState == Player.STATE_BUFFERING) {
                        progressBar.setVisibility(View.VISIBLE);
                    } else {
                        progressBar.setVisibility(View.GONE);
                    }
                }
                
//                @Override
//                public void onPlayerError(ExoPlaybackException error) {
//                    String errorMessage;
//                    switch (error.type) {
//                        case ExoPlaybackException.TYPE_SOURCE:
//                            errorMessage = "视频源错误: " + error.getSourceException().getMessage();
//                            break;
//                        case ExoPlaybackException.TYPE_RENDERER:
//                            errorMessage = "渲染错误: " + error.getRendererException().getMessage();
//                            break;
//                        case ExoPlaybackException.TYPE_UNEXPECTED:
//                            errorMessage = "意外错误: " + error.getUnexpectedException().getMessage();
//                            break;
//                        case ExoPlaybackException.TYPE_REMOTE:
//                            errorMessage = "远程错误";
//                            break;
//                        default:
//                            errorMessage = "未知错误";
//                            break;
//                    }
//
//                    Log.e(TAG, "播放错误: " + errorMessage, error);
//                    Toast.makeText(VideoPlayerActivity.this, "播放错误: " + errorMessage, Toast.LENGTH_LONG).show();
//                }
            });
        }

        // 创建媒体源
        MediaSource mediaSource = buildMediaSource(Uri.parse(streamUrl));
        
        // 设置播放器状态
        player.setPlayWhenReady(playWhenReady);
        player.seekTo(currentWindow, playbackPosition);
        
        // 准备并播放
        player.prepare(mediaSource, false, false);
        
        Log.d(TAG, "播放器初始化完成，开始播放");
    }
    
    /**
     * 根据URI创建媒体源
     * @param uri 媒体URI
     * @return 媒体源
     */
    private MediaSource buildMediaSource(Uri uri) {
        String userAgent = Util.getUserAgent(this, "WarmSDG");
        
        // 检查是否是HLS流
        if (streamUrl.contains(".m3u8")) {
            // 创建HLS媒体源
            return new HlsMediaSource.Factory(
                    new DefaultHttpDataSource.Factory()
                            .setUserAgent(userAgent)
                            .setAllowCrossProtocolRedirects(true))
                    .createMediaSource(MediaItem.fromUri(uri));
        } else {
            // 创建普通媒体源
            DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this, userAgent);
            return new ProgressiveMediaSource.Factory(dataSourceFactory)
                    .createMediaSource(MediaItem.fromUri(uri));
        }
    }
    
    /**
     * 释放播放器资源
     */
    private void releasePlayer() {
        if (player != null) {
            // 保存播放状态
            playWhenReady = player.getPlayWhenReady();
            playbackPosition = player.getCurrentPosition();
            currentWindow = player.getCurrentWindowIndex();
            
            // 释放播放器
            player.release();
            player = null;
            
            Log.d(TAG, "播放器资源已释放");
        }
    }
    
    /**
     * 切换全屏模式
     */
    private void toggleFullscreen() {
        // 这里可以实现全屏切换逻辑
        // 例如隐藏/显示系统UI，旋转屏幕等
        
        // 简单实现：切换系统UI可见性
        int newVisibility;
        if ((getWindow().getDecorView().getSystemUiVisibility() & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
            // 进入全屏
            newVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            fullscreenButton.setImageResource(R.drawable.ic_fullscreen_exit);
        } else {
            // 退出全屏
            newVisibility = View.SYSTEM_UI_FLAG_VISIBLE;
            fullscreenButton.setImageResource(R.drawable.ic_fullscreen);
        }
        
        getWindow().getDecorView().setSystemUiVisibility(newVisibility);
    }
} 